from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import pymysql
import utility_function
import sys


ip="localhost"
user_name="root"
password="****"     # 输入数据库密码
databas="booksalingsystem"

class log_in(QWidget):
    def __init__(self):
        super().__init__()
        self.success=False
        self.conn = pymysql.connect(host=ip, user=user_name, password=password, database=databas, charset="utf8")
        self.initUI()
    def initUI(self):
        user_name=QLabel('user name:')
        password=QLabel('password:')
        user_name_edit = QLineEdit()
        password_edit = QLineEdit()
        user_name_edit.textChanged[str].connect(self.input_user_name)
        password_edit.textChanged[str].connect(self.input_password)
        password_edit.setEchoMode(QLineEdit.Password)
        btn = QPushButton('确定')
        btn.clicked.connect(self.check_userpassword)
        self.lerror=QLabel('')
        grid = QGridLayout()
        grid.addWidget(user_name, 0, 0)
        grid.addWidget(user_name_edit, 0, 1)
        grid.addWidget(password, 1, 0)
        grid.addWidget(password_edit, 1, 1)
        grid.addWidget(self.lerror,2,1)
        grid.addWidget(btn,2,2)
        grid.setColumnStretch(0, 2)
        grid.setColumnStretch(1, 4)
        self.setLayout(grid)
        self.resize(400, 200)
        self.center()
        self.setWindowTitle('Log in')

    def check_userpassword(self):
        cursor = self.conn.cursor()
        self.success = False
        sqlsentence = """select * from booksalingsystem.usertable where username='{}' and password='{}';""".format(
            self.user_name, self.password)
        qnum = cursor.execute(sqlsentence)
        cursor.close()
        if qnum != 0:
            self.success = True
        if self.success:
            self.close()
            # print("user name: " + self.user_name)
            # print("password: " + self.password)
        else:
            self.lerror.setText('用户名或密码错误')

    def closeEvent(self, event):
        self.conn.close()
        event.accept()
    def input_user_name(self, text):
        self.user_name=text
    def input_password(self, text):
        self.password=text
    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
    def get_re(self):
        return self.success


class jinhuoWidget(QWidget):
    def __init__(self,uf):
        super().__init__()
        self.uf = uf
        self.initUI()

    def initUI(self):
        self.booknameLable = QLabel("书名")
        self.booknameEdit = QLineEdit()
        self.booknameEdit.textChanged[str].connect(self.input_bookname)
        self.jinhuobtn = QPushButton('进货')
        self.jinhuobtn.clicked.connect(self.jinhuoButtonClicked)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(self.booknameLable)
        hbox.addWidget(self.booknameEdit)
        hbox.addWidget(self.jinhuobtn)
        hbox.addStretch(1)

        self.successText = QLabel("")
        self.IDText = QLabel("")
        self.datetimeText = QLabel("")
        self.numText = QLabel("")
        self.priceText = QLabel("")

        textbox = QVBoxLayout()
        textbox.addWidget(self.successText)
        textbox.addWidget(self.IDText)
        textbox.addWidget(self.datetimeText)
        textbox.addWidget(self.numText)
        textbox.addWidget(self.priceText)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox)
        vbox.addStretch(1)
        vbox.addLayout(textbox)
        vbox.addStretch(1)

        self.setLayout(vbox)

    def input_bookname(self, text):
        self.bookname = text

    def jinhuoButtonClicked(self):

        if self.booknameEdit.text() == "":
            return
        try:
            success, info = self.uf.jinhuo(self.bookname)

            if success:
                self.successText.setText("进货成功。进货单信息: ")
                self.IDText.setText("JID: {}; BID: {}; SID: {}".format(info[0], info[1], info[2]))
                self.datetimeText.setText("进货时间: {}".format(info[3]))
                self.numText.setText("进货数量: {}".format(info[4]))
                self.priceText.setText("进货单价: {}".format(info[5]))
            else:
                self.successText.setText(str(info))
        except Exception as e:
            print(e)

class tuihuoWidget(QWidget):
    def __init__(self,uf):
        super().__init__()
        self.uf = uf
        self.num=0
        self.xiaoshouid = 0
        self.initUI()
    def initUI(self):
        self.ltuihuodan=QLabel("")
        self.lsuccess=QLabel("")
        lxiaoshouid = QLabel('销售id:')
        lnum = QLabel('数量:')
        xiaoshouid = QLineEdit()
        xiaoshouid.textChanged[str].connect(self.input_xiaoshouid)
        xiaoshouid.setMaxLength(5)
        num = QLineEdit()
        num.textChanged[str].connect(self.input_num)
        num.setMaxLength(5)
        btn = QPushButton('退货')
        btn.clicked.connect(self.tuihu)
        vbox = QVBoxLayout()
        vbox.addStretch(1)
        hbox1 = QHBoxLayout()
        hbox1.addStretch(1)
        hbox1.addWidget(lxiaoshouid)
        hbox1.addStretch(1)
        hbox1.addWidget(xiaoshouid)
        hbox1.addStretch(1)
        vbox.addLayout(hbox1)
        vbox.addStretch(1)
        hbox2 = QHBoxLayout()
        hbox2.addStretch(1)
        hbox2.addWidget(lnum)
        hbox2.addStretch(1)
        hbox2.addWidget(num)
        hbox2.addStretch(1)
        vbox.addLayout(hbox2)
        vbox.addStretch(1)
        hbox3 = QHBoxLayout()
        hbox3.addStretch(1)
        hbox3.addWidget(btn)
        hbox3.addStretch(1)
        vbox.addLayout(hbox3)
        vbox.addStretch(1)
        hbox4 = QHBoxLayout()
        hbox4.addStretch(1)
        hbox4.addWidget(self.lsuccess)
        hbox4.addStretch(1)
        vbox.addLayout(hbox4)
        vbox.addStretch(1)
        hbox5 = QHBoxLayout()
        hbox5.addStretch(1)
        hbox5.addWidget(self.ltuihuodan)
        hbox5.addStretch(1)
        vbox.addLayout(hbox5)
        vbox.addStretch(1)
        self.setLayout(vbox)


    def print(self):
        text = self.uf.printtid(self.tid)
        tid = str(text[0])
        bid = str(text[1])
        cid = str(text[2])
        dt = text[3]
        num = str(text[4])
        self.ltuihuodan.setText(
            "退货id:" + tid + ",书id:" + bid + ",顾客id:" + cid + ",时间:" + str(dt.year) + "." + str(dt.month) + "." + str(
                dt.day) + "." + str(dt.hour) + ":" + str(dt.minute) + ":" + str(
                dt.second) + ",退货数量:" + num)

    def tuihu(self):
        try:
            [success, self.tid] = self.uf.tuihuo(self.xiaoshouid, self.num)
        except Exception as e:
            print(e)
        if success == True:
            self.lsuccess.setText('退货成功')
            self.print()
        else:
            self.lsuccess.setText('退货失败')
            self.ltuihuodan.setText("")

    def input_xiaoshouid(self,text):
        self.ltuihuodan.setText("")
        self.lsuccess.setText("")
        try:
            self.xiaoshouid=int(text)
        except Exception as e:
            self.xiaoshouid=0

    def input_num(self, text):
        self.ltuihuodan.setText("")
        self.lsuccess.setText("")
        try:
            self.num=int(text)
        except Exception as e:
            self.num=0

class tongjiWidget(QWidget):
    def __init__(self, uf):
        super().__init__()
        self.uf = uf
        self.initUI()

    def initUI(self):
        hbox = QHBoxLayout()
        vbox = QVBoxLayout()
        month = QLabel('月份:')
        self.btn = QPushButton('搜索')
        self.btn.clicked.connect(self.buttonClicked)
        self.month_edit = QLineEdit(self)
        self.month_edit.textChanged[str].connect(self.input_user_month)
        self.month_edit.setMaxLength(5)
        hbox.addStretch(1)
        hbox.addWidget(month)
        hbox.addWidget(self.month_edit)
        hbox.addWidget(self.btn)
        hbox.addStretch(1)
        vbox.addLayout(hbox)
        self.model = QStandardItemModel(0, 3)
        self.model.setHorizontalHeaderLabels(['书名', '书本销售量', '书本销售额'])
        tableview = QTableView()
        tableview.setModel(self.model)
        tableview.horizontalHeader().setStretchLastSection(True)
        tableview.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        vbox.addWidget(tableview)
        self.setLayout(vbox)

    def buttonClicked(self):
        self.cleardata()
        if (self.month_edit.text() == ""):
            result = self.uf.monthofbook("")
            for i in range(0, len(result)):
                self.model.appendRow([
                    QStandardItem(result[i][0]),
                    QStandardItem("%d" % result[i][1]),
                    QStandardItem("%f" % result[i][2])
                ])
                for j in range(0, 3):
                    self.model.item(i, j).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
        else:

            result = self.uf.monthofbook(self.month_edit.text())

            for i in range(0, len(result)):
                self.model.appendRow([
                    QStandardItem(result[i][0]),
                    QStandardItem("%d" % result[i][1]),
                    QStandardItem("%f" % result[i][2])
                ])
                for j in range(0, 3):
                    self.model.item(i, j).setTextAlignment(Qt.AlignmentFlag.AlignCenter)

    def cleardata(self):
        self.model.clear()
        self.model.setHorizontalHeaderLabels(['书名', '书本销售量', '书本销售额'])

    def input_user_month(self, text):
        self.month = text


class xiaoshouWidget(QWidget):
    def __init__(self,uf):
        super().__init__()
        self.uf = uf
        self.cid = 0
        self.num = 0
        self.bookname=""
        self.initUI()
    def initUI(self):
        self.lkucun = QLabel("")
        self.lsuccess = QLabel("")
        self.lxiaoshoudan = QLabel("")
        lbookname = QLabel('书名:')
        lnum = QLabel('数量:')
        lcid = QLabel('顾客id:')
        bookname=QLineEdit()
        bookname.textChanged[str].connect(self.input_bookname)
        bookname.setMaxLength(5)
        num = QLineEdit()
        num.textChanged[str].connect(self.input_num)
        num.setMaxLength(5)
        cid = QLineEdit()
        cid.textChanged[str].connect(self.input_cid)
        cid.setMaxLength(5)
        btn = QPushButton('销售')
        btn.clicked.connect(self.xiaosho)
        vbox=QVBoxLayout()
        vbox.addStretch(1)
        hbox1=QHBoxLayout()
        hbox1.addStretch(1)
        hbox1.addWidget(lbookname)
        hbox1.addStretch(1)
        hbox1.addWidget(bookname)
        hbox1.addStretch(1)
        vbox.addLayout(hbox1)
        vbox.addStretch(1)
        hbox2=QHBoxLayout()
        hbox2.addStretch(1)
        hbox2.addWidget(lnum)
        hbox2.addStretch(1)
        hbox2.addWidget(num)
        hbox2.addStretch(1)
        vbox.addLayout(hbox2)
        vbox.addStretch(1)
        hbox3=QHBoxLayout()
        hbox3.addStretch(1)
        hbox3.addWidget(lcid)
        hbox3.addStretch(1)
        hbox3.addWidget(cid)
        hbox3.addStretch(1)
        vbox.addLayout(hbox3)
        vbox.addStretch(1)
        hbox4=QHBoxLayout()
        hbox4.addStretch(1)
        hbox4.addWidget(self.lkucun)
        hbox4.addStretch(1)
        vbox.addLayout(hbox4)
        vbox.addStretch(1)
        hbox5=QHBoxLayout()
        hbox5.addStretch(1)
        hbox5.addWidget(self.lsuccess)
        hbox5.addStretch(1)
        vbox.addLayout(hbox5)
        vbox.addStretch(1)
        hbox6=QHBoxLayout()
        hbox6.addStretch(1)
        hbox6.addWidget(self.lxiaoshoudan)
        hbox6.addStretch(1)
        vbox.addLayout(hbox6)
        vbox.addStretch(1)
        hbox7=QHBoxLayout()
        hbox7.addStretch(1)
        hbox7.addWidget(btn)
        hbox7.addStretch(1)
        vbox.addLayout(hbox7)
        vbox.addStretch(1)
        self.setLayout(vbox)

    def input_bookname(self, text):
        self.lsuccess.setText('')
        self.lxiaoshoudan.setText('')
        self.bookname=text
        self.kucunf()

    def input_num(self, text):
        self.lsuccess.setText('')
        self.lxiaoshoudan.setText('')
        try:
            self.num = int(text)
        except Exception as e:
            self.num=0

    def input_cid(self, text):
        self.lsuccess.setText('')
        self.lxiaoshoudan.setText('')
        try:
            self.cid=int(text)
        except Exception as e:
            self.cid=0

    def xiaosho(self):
        [success,self.xid]=self.uf.xiaoshou(self.bookname,self.num,self.cid)
        if success==True:
            self.lsuccess.setText('交易成功')
            self.kucunf()
            self.print()
        else:
            self.lxiaoshoudan.setText('')
            self.lsuccess.setText('交易失败')

    def kucunf(self):
        [b, n] = self.uf.kucun(self.bookname)
        if (b == False):
            self.lkucun.setText('不存在此书')
        else:
            self.lkucun.setText('库存：' + str(n))

    def print(self):
        text=self.uf.printxid(self.xid)
        xid=str(text[0])
        bid=str(text[1])
        cid=str(text[2])
        dt=text[3]
        up=str(text[4])
        num=str(text[5])
        self.lxiaoshoudan.setText("销售id:"+xid+",书id:"+bid+",顾客id:"+cid+",时间:"+str(dt.year)+"."+str(dt.month)+"."+str(dt.day)+"."+str(dt.hour)+":"+str(dt.minute)+":"+str(dt.second)+",单价:"+up+",购买数量:"+num)

class window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.uf=utility_function.utility_function(username=user_name, password=password, host=ip, d=databas)
        self.initUI()

    def initUI(self):
        jinAction = QAction(QIcon('8.png'), '&进货', self)
        jinAction.setStatusTip('进货')
        jinAction.triggered.connect(self.jin)

        tuiAction = QAction(QIcon('8.png'), '&退货', self)
        tuiAction.setStatusTip('退货')
        tuiAction.triggered.connect(self.tui)

        tongAction = QAction(QIcon('8.png'), '&统计', self)
        tongAction.setStatusTip('统计')
        tongAction.triggered.connect(self.tong)

        xiaoAction = QAction(QIcon('8.png'), '&销售', self)
        xiaoAction.setStatusTip('销售')
        xiaoAction.triggered.connect(self.xiao)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&menu')
        fileMenu.addAction(jinAction)
        fileMenu.addAction(tuiAction)
        fileMenu.addAction(tongAction)
        fileMenu.addAction(xiaoAction)

        self.setCentralWidget(jinhuoWidget(self.uf))

        self.setWindowTitle('book sale')
        self.resize(600, 600)

    def jin(self):
        self.setCentralWidget(jinhuoWidget(self.uf))
    def tui(self):
        self.setCentralWidget(tuihuoWidget(self.uf))
    def tong(self):
        self.setCentralWidget(tongjiWidget(self.uf))
    def xiao(self):
        self.setCentralWidget(xiaoshouWidget(self.uf))

    def closeEvent(self, event):
        reply = QMessageBox.question(self, 'Message',
                                     "Are you sure to quit?", QMessageBox.Yes |
                                     QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.uf.close()
            event.accept()
        else:
            event.ignore()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    d_log_in=log_in()
    d_log_in.show()
    app.exec_()
    re=d_log_in.get_re()
    if(re==True):
        d_window=window()
        d_window.show()
        sys.exit(app.exec_())
